﻿#include "configfile.h"
#include <QSettings>
#include <QFile>
#include <QNetworkInterface>
#include <QHostInfo>
#include <commonfuc.h>
#include "oeasykey.h"
#define SCOPE(val, min, max) {if(*val<min) *val=min; if(*val>max) *val=max;}

ConfigFile::ConfigFile(const char *path) : m_cfg(), cfgPath(path)
{
    cfgPath.clear();
    QString strRoot = CommonFuc::getAppDirPath();
    cfgPath.append(strRoot);
    cfgPath.append("oeasycfg.ini");

    QSettings settings(cfgPath, QSettings::IniFormat);

    //keyinfo
    int maxface = 1;
    int maxtarget = 0;
    int maxcar = 0;
    m_cfg.keyinfo.oeasykey = settings.value("oeasykey", "").toString();
    OeasyKey::parseKey(m_cfg.keyinfo.oeasykey, maxface, maxtarget, maxcar);
    QString realkey = OeasyKey::generaKey(maxface, maxtarget, maxcar);

    bool ok = OeasyKey::checkKey(m_cfg.keyinfo.oeasykey); //key check
    if(ok && realkey == m_cfg.keyinfo.oeasykey) // limit check,avoiding user changing limit numner
    {
        m_cfg.keyinfo.bvalid = true;
        m_cfg.keyinfo.maxFaceChannel = maxface;
        m_cfg.keyinfo.maxTargetChannel = maxtarget;
        m_cfg.keyinfo.maxCarChannel = maxcar;
    }

    m_cfg.general.faceJpgRecvPort = settings.value("faceJpgRecvPort", 10101).toInt();
    m_cfg.general.intercomPort = settings.value("intercomPort", 12301).toInt();
#ifdef QT_NO_DEBUG
    m_cfg.general.picUrl = settings.value("picUrl", "https://security.0easy.com/img/").toString();
    m_cfg.general.tmpPicUrl = settings.value("tmpPicUrl", "http://zimg.0easy.com:6400").toString();
    m_cfg.general.reportUrl = settings.value("reportUrl", "https://security.0easy.com/yihao01-alarm-monitor/device_report").toString();
    m_cfg.general.bigDataUrl = settings.value("bigDataUrl", "http://bigdata.0easy.com/log/cameraNew").toString();
    m_cfg.general.proxyUrl = settings.value("proxyUrl", "ws://smart.0easy.com:6000").toString();
#else
    m_cfg.general.picUrl = settings.value("picUrl", "http://192.168.5.136:48069").toString();
    m_cfg.general.tmpPicUrl = settings.value("tmpPicUrl", "http://192.168.5.136:48068").toString();
    m_cfg.general.reportUrl = settings.value("reportUrl", "http://192.168.7.77:8000/device_report").toString();
    m_cfg.general.bigDataUrl = settings.value("bigDataUrl", "http://192.168.0.235:7890/log/cameraNew").toString();
    m_cfg.general.proxyUrl = settings.value("proxyUrl", "ws://192.168.5.136:6666").toString();
#endif
    m_cfg.general.proxyId.sprintf("%010d", settings.value("proxyId", "0000002050").toInt());
    m_cfg.general.postTimeout = settings.value("postTimeout", 3000).toInt();
    m_cfg.general.postFailNum = settings.value("postFailNum", 3).toInt();
    m_cfg.general.saveVideoTForward = settings.value("saveVideoTForward", 10).toInt();
    m_cfg.general.saveVideoTBack = settings.value("saveVideoTBack", 10).toInt();
    SCOPE(&m_cfg.general.saveVideoTForward, 0, 60);//使用NET_DVR_GetFileByTime_V40从nvr获取视频时最大限制为1024MB，为了不超所以限定了大小
    SCOPE(&m_cfg.general.saveVideoTBack, 0, 60);
    m_cfg.general.nOpenDataSourceMode = settings.value("OpenDataSourceMode", 0).toInt();
    m_cfg.general.nOpenVideoStoreMode = settings.value("OpenVideoStoreMode", 0).toInt();
    if(0 != m_cfg.general.nOpenDataSourceMode && 1 != m_cfg.general.nOpenDataSourceMode)
    {
        m_cfg.general.nOpenDataSourceMode = 0;
    }
    if(0 != m_cfg.general.nOpenVideoStoreMode && 1 != m_cfg.general.nOpenVideoStoreMode)
    {
        m_cfg.general.nOpenVideoStoreMode = 0;
    }

    settings.beginGroup("car");
    m_cfg.car.url = settings.value("url", "https://smart.0easy.com/dump").toString();
    m_cfg.car.enterUrl = "";
    m_cfg.car.filterPath = settings.value("filterPath", "car.exe").toString();
    m_cfg.car.filterPort = settings.value("filterPort", 10200).toInt();
    m_cfg.car.postWidth = settings.value("postWidth", 300).toInt();
    m_cfg.car.postHeight = settings.value("postHeight", 300).toInt();
    m_cfg.car.successGap = settings.value("successGap", 5).toInt();
    m_cfg.car.failedGap = 0xfffffff;
    m_cfg.car.filter = settings.value("filter", false).toBool();
    m_cfg.car.saveFilterJpg = settings.value("saveFilterJpg", false).toBool();
    settings.endGroup();

    settings.beginGroup("face");
    m_cfg.face.url = settings.value("url", "http://192.168.7.77:9317/compare").toString();
    m_cfg.face.enterUrl = settings.value("enterUrl", "http://192.168.7.77:9317/distribute").toString();
    m_cfg.face.filterPath = settings.value("filterPath", "face.exe").toString();
    m_cfg.face.filterPort = settings.value("filterPort", 10100).toInt();
    m_cfg.face.postWidth = settings.value("postWidth", 640).toInt();
    m_cfg.face.postHeight = settings.value("postHeight", 480).toInt();
    m_cfg.face.successGap = settings.value("successGap", 5).toInt();
    m_cfg.face.failedGap = settings.value("failedGap", 5).toInt();
    m_cfg.face.filter = settings.value("filter", false).toBool();
    m_cfg.face.saveFilterJpg = settings.value("saveFilterJpg", false).toBool();
    settings.endGroup();

    settings.beginGroup("target");
    m_cfg.target.ip = settings.value("ip", "127.0.0.1").toString();
    m_cfg.target.port = settings.value("port", 7003).toInt();
    m_cfg.target.gap = settings.value("gap", 1).toInt();
    m_cfg.target.alarm_gap = settings.value("alarm_gap", 300).toInt();
    m_cfg.target.alarm_threshold1 = settings.value("alarm_threshold1", 12).toInt();
    m_cfg.target.alarm_threshold2 = settings.value("alarm_threshold2", 10).toInt();
    m_cfg.target.alarm_threshold3 = settings.value("alarm_threshold3", 8).toInt();
    m_cfg.target.alarm_threshold4 = settings.value("alarm_threshold4", 6).toInt();
    m_cfg.target.alarm_distance = settings.value("alarm_distance", -1).toInt();
    settings.endGroup();

    SCOPE(&m_cfg.general.faceJpgRecvPort, 1, 65535);
    SCOPE(&m_cfg.car.filterPort, 1, 65535);
    SCOPE(&m_cfg.face.filterPort, 1, 65535);
    SCOPE(&m_cfg.general.postTimeout, 1000, 60000);
    SCOPE(&m_cfg.general.postFailNum, 0, 10);


    //add by liangshuchao 2017.07.12
    settings.beginGroup("transfer_clouds");
    m_cfg.transferInfo.qiniuZone = settings.value("qiniuZone", 0).toInt();//bucket
    m_cfg.transferInfo.bucket = settings.value("bucket", "video").toString();
    m_cfg.transferInfo.transcodeBucket = settings.value("bucket", "video").toString();
    m_cfg.transferInfo.accessKey = settings.value("accessKey", "63LAFMMKCMPxne0C1RafN-X1PvsKMNHghDM3cYSD").toString();
    m_cfg.transferInfo.secretkey = settings.value("secretkey", "S0WhkmqcKkrX1G8WDV2rJJhVnTSKieaztR3xdDUX").toString();
    m_cfg.transferInfo.externLink = settings.value("externLink", "http://oswxl4ccb.bkt.clouddn.com/").toString();
    m_cfg.transferInfo.expires = settings.value("expires", 3600).toInt();
    m_cfg.transferInfo.persistentOps = settings.value("persistentOps", "avthumb/mp4/vcodec/libx264|saveas/").toString();
    m_cfg.transferInfo.persistentPipeline = settings.value("persistentPipeline", "oeasy_test").toString();
    m_cfg.transferInfo.backstageUrl = settings.value("backstageUrl", "http://192.168.0.235:7890/log/cameraNew?msgJson=").toString();
    m_cfg.transferInfo.picUrl = settings.value("picUrl", "192.168.5.136:48069/upload").toString();
    settings.endGroup();

    settings.beginGroup("transfer_localAreaNetwork");
    m_cfg.transferInfo.transcode = settings.value("transcode", "-vcodec libx264 -s 640x480 -vb 800k -acodec aac -ab 96000 -ar 48000 -ac 2 -f flv").toString();
    m_cfg.transferInfo.ffmpegPath = settings.value("ffmpegPath", "./ffmpeg/ffmpeg").toString();
    m_cfg.transferInfo.srcVideoDirPath = settings.value("srcVideoDirPath", "./record/").toString();
    m_cfg.transferInfo.targetVideoDirPath = settings.value("targetVideoDirPath", "../../doc/").toString();
    settings.endGroup();

    settings.beginGroup("log");
    m_cfg.logInfo.logFileName = settings.value("logFileName", "OeasyProxy").toString();
    m_cfg.logInfo.logSize = settings.value("logSize", 1000).toInt();
    settings.endGroup();


    settings.beginGroup("IsUseNvr");
    m_cfg.bUseNvr= settings.value("IsUseNvr", 1).toBool();
    settings.endGroup();


    int size = settings.beginReadArray("nvr");
    int i = 0;
	while (i < size)
    {
        STRUCT_NVR_INFO nvr;

        settings.setArrayIndex(i);
        nvr.ip = settings.value("ip", "192.168.0.64").toString();
        nvr.username = settings.value("username", "admin").toString();
        nvr.password = settings.value("password", "oeasy123").toString();
        nvr.port = settings.value("port", 8000).toInt();
        nvr.IPChanNum = settings.value("IPChanNum", 0).toInt();
        nvr.startDChan = settings.value("startDChan", 0).toInt();

        m_cfg.nvrList.append(nvr);
		i++;
	}
	settings.endArray();
	
	i=0;
	size = settings.beginReadArray("ipc");
    while (i < size)
    {
        STRUCT_IPC_INFO ipc;

        settings.setArrayIndex(i);
        m_IpcMap[i] = settings.value("intercomMac", "").toString();
        ipc.intercomMac = settings.value("intercomMac", "").toString();
        ipc.doorInfo = settings.value("doorInfo", "").toString();
        ipc.ip = settings.value("ip", "192.168.1.131").toString();
        ipc.username = settings.value("username", "admin").toString();
        ipc.password = settings.value("password", "oeasy123456").toString();
        ipc.cameraId.sprintf("%s_%04d",m_cfg.general.proxyId.toStdString().c_str(),i);//例如：0000004228_0001
        ipc.port = settings.value("port", 8000).toInt();
        ipc.parentNVR = settings.value("parentNVR", 0).toInt();
        ipc.NVRChannel = settings.value("NVRChannel", 0).toInt();
        ipc.type = settings.value("type", 0).toInt();
        ipc.picQuality = settings.value("picQuality", 50).toInt();
        ipc.recognitionFrame = settings.value("recognitionFrame", 1).toInt();
        ipc.motionStartX = settings.value("motionStartX", 0).toInt();
        ipc.motionStartY = settings.value("motionStartY", 0).toInt();
        ipc.motionWidth = settings.value("motionWidth", 22).toInt();
        ipc.motionHeight = settings.value("motionHeight", 18).toInt();
        ipc.motionSensitive = settings.value("motionSensitive", 1).toInt();
        ipc.SMSStreamType = settings.value("SMSStreamType", 0).toInt();

        SCOPE(&ipc.type, 0, 1 << IPC_TYPE_NUM);
        SCOPE(&ipc.picQuality, 1, 100);
        SCOPE(&ipc.recognitionFrame, 1, 3);
        SCOPE(&ipc.motionStartX, ipc.recognitionFrame, (20 - ipc.recognitionFrame));
        SCOPE(&ipc.motionStartY, ipc.recognitionFrame, (16 - ipc.recognitionFrame));
        SCOPE(&ipc.motionWidth, 1, (22 - ipc.recognitionFrame - ipc.motionStartX));
        SCOPE(&ipc.motionHeight, 1, (18 - ipc.recognitionFrame - ipc.motionStartY));
        SCOPE(&ipc.motionSensitive, 1, 5);

        m_cfg.ipcList.append(ipc);
        i++;
    }
    settings.endArray();

    settings.beginGroup("UploadOpenDoorInfor");
    m_cfg.transferInfo.UploadInforUrl = settings.value("UploadInforUrl", "http://127.0.0.1:7887/UploadOpenDoorInfor").toString();
    m_cfg.transferInfo.UploadInforPort = settings.value("UploadInforPort", 7887).toInt();
    m_cfg.logInfo1.logFileName = settings.value("logFileName", "UpOpen123").toString();
    m_cfg.logInfo1.logSize = settings.value("logSize", 1000).toInt();
    settings.endGroup();
}

ConfigFile* ConfigFile::m_sconfig = Q_NULLPTR;
QMutex ConfigFile::m_smutex;

ConfigFile &ConfigFile::getInstance()
{
    m_smutex.lock();
    if(m_sconfig == Q_NULLPTR)
    {
        m_sconfig = new ConfigFile();
    }
    m_smutex.unlock();
    return *m_sconfig;
}

int ConfigFile::SetConfig(STRUCT_OEASY_CONFIG tmp)
{
    QSettings settings(cfgPath, QSettings::IniFormat);

    settings.clear();
    settings.setValue("oeasykey", tmp.keyinfo.oeasykey);
    settings.setValue("faceJpgRecvPort", tmp.general.faceJpgRecvPort);
    settings.setValue("intercomPort", tmp.general.intercomPort);
    settings.setValue("picUrl", tmp.general.picUrl);
    settings.setValue("tmpPicUrl", tmp.general.tmpPicUrl);
    settings.setValue("reportUrl", tmp.general.reportUrl);
    settings.setValue("bigDataUrl", tmp.general.bigDataUrl);
    settings.setValue("proxyUrl", tmp.general.proxyUrl);
    settings.setValue("proxyId", tmp.general.proxyId);
    settings.setValue("postTimeout", tmp.general.postTimeout);
    settings.setValue("postFailNum", tmp.general.postFailNum);
//    settings.setValue("saveVideoTForward", tmp.general.saveVideoTForward);
//    settings.setValue("saveVideoTBack", tmp.general.saveVideoTBack);
    int forwardT=m_cfg.general.saveVideoTForward;
    int backT=m_cfg.general.saveVideoTBack;
    SCOPE(&forwardT, 0, 60);
    SCOPE(&backT, 0, 60);
    settings.setValue("saveVideoTForward", forwardT);
    settings.setValue("saveVideoTBack", backT);

    int nOpenDataSourceMode = m_cfg.general.nOpenDataSourceMode;
    int nOpenVideoStoreMode = m_cfg.general.nOpenVideoStoreMode;
    if(0 != nOpenDataSourceMode && 1 != nOpenDataSourceMode)
    {
        nOpenDataSourceMode = 0;
    }
    if(0 != nOpenVideoStoreMode && 1 != nOpenVideoStoreMode)
    {
        nOpenVideoStoreMode = 0;
    }
    settings.setValue("OpenDataSourceMode", nOpenDataSourceMode);
    settings.setValue("OpenVideoStoreMode", nOpenVideoStoreMode);


    settings.beginGroup("car");
    settings.setValue("url", tmp.car.url);
    settings.setValue("filterPath", tmp.car.filterPath);
    settings.setValue("filterPort", tmp.car.filterPort);
    settings.setValue("postWidth", tmp.car.postWidth);
    settings.setValue("postHeight", tmp.car.postHeight);
    settings.setValue("successGap", tmp.car.successGap);
    settings.setValue("filter", tmp.car.filter);
    settings.setValue("saveFilterJpg", tmp.car.saveFilterJpg);
    settings.endGroup();

    settings.beginGroup("face");
    settings.setValue("url", tmp.face.url);
    settings.setValue("enterUrl", tmp.face.enterUrl);
    settings.setValue("filterPath", tmp.face.filterPath);
    settings.setValue("filterPort", tmp.face.filterPort);
    settings.setValue("postWidth", tmp.face.postWidth);
    settings.setValue("postHeight", tmp.face.postHeight);
    settings.setValue("successGap", tmp.face.successGap);
    settings.setValue("failedGap", tmp.face.failedGap);
    settings.setValue("filter", tmp.face.filter);
    settings.setValue("saveFilterJpg", tmp.face.saveFilterJpg);
    settings.endGroup();

    settings.beginGroup("target");
    settings.setValue("ip", tmp.target.ip);
    settings.setValue("port", tmp.target.port);
    settings.setValue("gap", tmp.target.gap);
    settings.setValue("alarm_gap", tmp.target.alarm_gap);
    settings.setValue("alarm_threshold1", tmp.target.alarm_threshold1);
    settings.setValue("alarm_threshold2", tmp.target.alarm_threshold2);
    settings.setValue("alarm_threshold3", tmp.target.alarm_threshold3);
    settings.setValue("alarm_threshold4", tmp.target.alarm_threshold4);
    settings.setValue("alarm_distance", tmp.target.alarm_distance);
    settings.endGroup();

    //add by liangshuchao 2017.07.12
    settings.beginGroup("transfer_clouds");
    settings.setValue("qiniuZone", tmp.transferInfo.qiniuZone);
    settings.setValue("transcodeBucket", tmp.transferInfo.transcodeBucket);
    settings.setValue("bucket", tmp.transferInfo.bucket);
    settings.setValue("accessKey", tmp.transferInfo.accessKey);
    settings.setValue("secretkey", tmp.transferInfo.secretkey);
    settings.setValue("externLink", tmp.transferInfo.externLink);
    settings.setValue("expires", tmp.transferInfo.expires);
    settings.setValue("persistentOps", tmp.transferInfo.persistentOps);
    settings.setValue("persistentPipeline", tmp.transferInfo.persistentPipeline);
    settings.setValue("backstageUrl", tmp.transferInfo.backstageUrl);
    settings.setValue("picUrl", tmp.transferInfo.picUrl);
    settings.endGroup();

    settings.beginGroup("transfer_localAreaNetwork");
    settings.setValue("transcode", tmp.transferInfo.transcode);
    settings.setValue("ffmpegPath", tmp.transferInfo.ffmpegPath);
    settings.setValue("srcVideoDirPath", tmp.transferInfo.srcVideoDirPath);
    settings.setValue("targetVideoDirPath", tmp.transferInfo.targetVideoDirPath);
    settings.endGroup();

    settings.beginGroup("log");
    settings.setValue("logFileName", tmp.logInfo.logFileName);
    settings.setValue("logSize", tmp.logInfo.logSize);
    settings.endGroup();

    settings.beginGroup("IsUseNvr");
    settings.setValue("IsUseNvr", tmp.bUseNvr);
    settings.endGroup();


    settings.beginWriteArray("nvr");
    for (int i = 0; i < tmp.nvrList.size(); i++)
    {
        settings.setArrayIndex(i);
        STRUCT_NVR_INFO *nvr = &(tmp.nvrList[i]);

        settings.setValue("ip", nvr->ip);
        settings.setValue("username", nvr->username);
        settings.setValue("password", nvr->password);
        settings.setValue("port", nvr->port);
        settings.setValue("IPChanNum", nvr->IPChanNum);
        settings.setValue("startDChan", nvr->startDChan);
    }
    settings.endArray();

    settings.beginWriteArray("ipc");
    for (int i = 0; i < tmp.ipcList.size(); i++)
    {
        settings.setArrayIndex(i);
        STRUCT_IPC_INFO *ipc = &(tmp.ipcList[i]);

        SCOPE(&ipc->type, 0, 1 << IPC_TYPE_NUM);
        SCOPE(&ipc->picQuality, 1, 100);
        SCOPE(&ipc->recognitionFrame, 1, 3);
        SCOPE(&ipc->motionStartX, ipc->recognitionFrame, (20 - ipc->recognitionFrame));
        SCOPE(&ipc->motionStartY, ipc->recognitionFrame, (16 - ipc->recognitionFrame));
        SCOPE(&ipc->motionWidth, 1, (22 - ipc->recognitionFrame - ipc->motionStartX));
        SCOPE(&ipc->motionHeight, 1, (18 - ipc->recognitionFrame - ipc->motionStartY));
        SCOPE(&ipc->motionSensitive, 1, 5);

        settings.setValue("intercomMac", ipc->intercomMac);
        settings.setValue("doorInfo", ipc->doorInfo);
        settings.setValue("ip", ipc->ip);
        settings.setValue("username", ipc->username);
        settings.setValue("password", ipc->password);
        settings.setValue("cameraId", ipc->cameraId);
        settings.setValue("port", ipc->port);
        settings.setValue("parentNVR", ipc->parentNVR);
        settings.setValue("NVRChannel", ipc->NVRChannel);
        settings.setValue("type", ipc->type);
        settings.setValue("picQuality", ipc->picQuality);
        settings.setValue("recognitionFrame", ipc->recognitionFrame);
        settings.setValue("motionStartX", ipc->motionStartX);
        settings.setValue("motionStartY", ipc->motionStartY);
        settings.setValue("motionWidth", ipc->motionWidth);
        settings.setValue("motionHeight", ipc->motionHeight);
        settings.setValue("motionSensitive", ipc->motionSensitive);
        settings.setValue("SMSStreamType", ipc->SMSStreamType);
    }
    settings.endArray();

    settings.beginGroup("UploadOpenDoorInfor");
    settings.setValue("UploadInforUrl", tmp.transferInfo.UploadInforUrl);
    settings.setValue("UploadInforPort", tmp.transferInfo.UploadInforPort);
    settings.setValue("logFileName", tmp.logInfo1.logFileName);
    settings.setValue("logSize", tmp.logInfo1.logSize);
    settings.endGroup();

    return 0;
}

int ConfigFile::SetSaveLogFile(QString & strFileName)
{
    m_cfg.logInfo.logFileName = strFileName;

    QSettings settings(cfgPath, QSettings::IniFormat);

    settings.setValue("log/logFileName", strFileName);

    return 0;
}

bool ConfigFile::isValid()
{
    return m_cfg.keyinfo.bvalid;
}
